package org.skydiveapp;

import org.skydiveapplibrary.ui.InterfaceManager;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.Constants;
import org.skydiveapplibrary.repository.LocationRepository;
import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.ui.LocationListAdapter;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class LocationListActivity extends BaseListActivity
{
	// data
	private boolean isDualDisplay;
	
    @Override 
    public void onCreate(Bundle savedInstanceState)
    { 
		SettingsRepository settingsRepository = new SettingsRepository(this);
		if (settingsRepository.getUseLightTheme())
			super.setTheme(R.style.SkydiveAppTheme_Light_SemiTransparent);
		
    	super.onCreate(savedInstanceState);
    	
    	getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
    	
    	InterfaceManager.getInstance().setSubtitleText(getSupportActionBar(), 
				getResources().getString(R.string.locations_label));
    	
    	isDualDisplay = this.findViewById(R.id.phoneLayout) == null;
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        
        loadData();
    }
    
    @Override
    public void onListItemClick(ListView lv, View view, int position, long id)
    {
    	Intent intent = new Intent(this, LocationEditActivity.class);
        intent.putExtra(Constants.EXTRA_LOCATION_ID, (int)id);
        startActivity(intent);    	
    }
    
    private void loadData()
    {
    	// populate
		LocationRepository repository = new LocationRepository(this);
		LocationListAdapter adapter = new LocationListAdapter(
				this,
				repository.getLocations());
		setListAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.menu_add, menu);
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    	menu.findItem(R.id.menu_back).setVisible(isDualDisplay);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int itemId = item.getItemId();
		if (itemId == R.id.menu_add)
		{
			Intent intent = new Intent(this, LocationEditActivity.class);
			startActivity(intent);
			return true;
		}
		else if (itemId == R.id.menu_back)
		{
			close();
			return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
    }
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
	}
} 